package com.lexed.carmanager.controllor;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lexed.carmanager.database.pojo.bean.UserRolm;
import com.lexed.carmanager.service.DriverService;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	
	private DriverService driverService = new DriverService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String re = driverService.login(username, password);
		
		ObjectMapper om = new ObjectMapper();
		
		UserRolm userRolm = om.readValue(re, UserRolm.class);
		System.out.println(userRolm);
		// 代表登录成功
		if(userRolm.getStatus() == 1){
			// 将信息存放在Session中
			HttpSession  httpSession = request.getSession();
			httpSession.setAttribute("userrolm", userRolm);
		}else if(userRolm.getStatus() == 0){ // 初始化用户
			// 获取session
			HttpSession  httpSession = request.getSession();
			// 设置session属性userid
			httpSession.setAttribute("userid", userRolm.getId());
		}
		
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().println(re);
	}

}
